<?php

if (! function_exists('form_type_list')) {
    function form_type_list()
    {
        return [
            'text'=>'输入框',
            'textarea'=>'文本框',
            'picture'=>'图片',
            'switch'=>'开关',
            'file'=>'文件',
            'checkbox'=>'复选框',
            'select'=>'下拉框',
        ];
    }
}
if (! function_exists('null_filter')) {
    function null_filter($arr)
    {
        foreach ($arr as $key => &$val) {
            if (is_array($val)) {
                $val = null_filter($val);
            } else {
                if ($val === null) {
                    unset($arr[$key]);
                }
            }
        }
        return $arr;
    }
}

if (! function_exists('make_tree')) {

    /**
     * @param $arr
     * @return array
     * $arr = array(
    array("id" => 1 , "pid" => 0 , 'cat' => '栏目一'),
    array("id" => 2 , "pid" => 0 , 'cat' => '栏目二'),
    array("id" => 3 , "pid" => 1 , 'cat' => '栏目三'),
    array("id" => 4 , "pid" => 2 , 'cat' => '栏目四'),
    array("id" => 5 , "pid" => 1 , 'cat' => '栏目五'),
    array("id" => 6 , "pid" => 5 , 'cat' => '栏目六'),
    array("id" => 7 , "pid" => 5 , 'cat' => '栏目七'),
    array("id" => 8 , "pid" => 6 , 'cat' => '栏目八'),
    array("id" => 9 , "pid" => 1 , 'cat' => '栏目九'),
    array("id" => 10 , "pid" => 0 , 'cat' => '栏目十'),
    array("id" => 11 , "pid" => 10 , 'cat' => '栏目十一'),
    array("id" => 12 , "pid" => 11 , 'cat' => '栏目十二'),
    array("id" => 13 , "pid" => 2 , 'cat' => '栏目十三'),
    array("id" => 14, "pid" => 13 , 'cat' => '栏目十四')
    );
     */
    function make_tree($arr){
        $refer = array();
        $tree = array();
        foreach($arr as $k => $v){
            $refer[$v['id']] = & $arr[$k];  //创建主键的数组引用
        }

        foreach($arr as $k => $v){
            $pid = $v['pid'];   //获取当前分类的父级id
            if($pid == 0){
                $tree[] = & $arr[$k];   //顶级栏目
            }else{
                if(isset($refer[$pid])){
                    $refer[$pid]['subcat'][] = & $arr[$k];  //如果存在父级栏目，则添加进父级栏目的子栏目数组中
                }
            }
        }

        return $tree;
    }
}

if (! function_exists('tree_category')) {
    function tree_category($cate, $lefthtml = '|— ', $parent_id = 0, $lvl = 0)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['lvl'] = $lvl + 1;
                $v['lefthtml'] = str_repeat($lefthtml, $lvl);
                $v['cat_name'] = $v['lefthtml'] . $v['title'];
                $arr[] = $v;
                $arr = array_merge($arr, tree_category($cate, $lefthtml, $v['id'], $lvl + 1));
            }
        }
        return $arr;
    }
}

if (! function_exists('object_to_array')) {

    function object_to_array($object) {
        //先编码成json字符串，再解码成数组
        return json_decode(json_encode($object), true);
    }
}



/**

 * @Description: 无限极分类一

 * @Author: Yang

 * @param $data  数据库数据

 * @param int $parent_id   父级ID

 * @return array

 */

function getTree1($data, $parent_id = 0)

{

    $tree = array();

    foreach ($data as $k => $v) {

        if ($v["parent_id"] == $parent_id) {

            unset($data[$k]);

            if (!empty($data)) {

                $children = getCategory($data, $v["id"]);

                if (!empty($children)) {

                    $v["_child"] = $children;

                }

            }

            $tree[] = $v;

        }

    }

    return $tree;

}





/**

 * @Description: 无限极分类二

 * @Author: Yang

 * @param $data   数据库数据

 * @param int $parent_id  父级ID

 * @param int $level  等级

 * @return array

 */

function getTree2($data, $parent_id = 0, $level = 0)

{

    static $tree = array();

    foreach ($data as $k => $v) {

        if ($v["parent_id"] == $parent_id) {

            $v["level"] = $level;

            $tree[] = $v;

            getTree($data, $v["id"], $level + 1);

        }

    }

    return $tree;

}



/**

 * @Description: 无限分类三：面包屑导航

 * @Author: Yang

 * @param $data  数据库数据

 * @param $id    分类ID

 * @return array

 */

function getCrumbsBar($data, $id) {
    static $tree = array();
    foreach ($data as $k => $v) {
        if ($v["id"] == $id) {
            getCrumbsBar($data, $v["parent_id"]);
            $tree[] = $v;
        }
    }
    return $tree;
}

function list_pages_level($data ,$id)
{
    $tree = array();
    foreach ($data as $k => $v) {
        if ($v["id"] == $id) {
            list_pages_level($data, $v["parent_id"]);
            $tree[] = $v;
        }
    }
    return $tree;
}

//组合多维数组
function tree_array($cate, $parent_id = 0, $name = 'child')
{
    $arr = [];
    foreach ($cate as $v) {
        if ($v['parent_id'] == $parent_id) {
            $v[$name] = tree_array($cate, $v['id'], $name);
            $arr[]    = $v;
        }
    }
    return $arr;
}

/**
 * 生成编号
 * @param $type
 * @return string
 */
function get_sn($type)
{
    switch ($type) {
        case 1:         //订单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 2:         //支付单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 3:         //商品编号
            $str = 'G' . substr(msectime() . rand(0, 5), 1);
            break;
        case 4:         //货品编号
            $str = 'P' . substr(msectime() . rand(0, 5), 1);
            break;
        case 5:         //售后单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 6:         //退款单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 7:         //退货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 8:         //发货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 9:         //提货单号
            //$str = 'T'.$type.substr(msectime().rand(0,5), 1);
            $chars    = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '2', '3', '4', '5', '6', '7', '8', '9'];
            $charsLen = count($chars) - 1;
            shuffle($chars);
            $str = '';
            for ($i = 0; $i < 6; $i++) {
                $str .= $chars[mt_rand(0, $charsLen)];
            }
            break;
        default:
            $str = substr(msectime() . rand(0, 9), 1);
    }
    return $str;
}
/**
 * 获取hash值
 * @return string
 */
function get_hash()
{
    $chars   = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
    $random  = $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)];
    $content = uniqid() . $random;
    return sha1($content);
}

function get_breadcrumb($id = null)
{
    $breadcrumb='';
    $uri = ltrim(request()->getRequestUri(),'/');
    $result= \Illuminate\Support\Facades\DB::table('menu')->where('uri',$uri)->first();

    if($id > 0)
    {
        $result= \Illuminate\Support\Facades\DB::table('menu')->where('id',$id)->first();
    }

    if($result)
    {
        //$result->title;
        $breadcrumb =  $result->title;

        if($result->parent_id > 0)
        {
            $breadcrumb .= '/' . get_breadcrumb($result->parent_id);
        }
    }

    $strArr=array_reverse(explode('/',$breadcrumb));

    return implode(' / ',$strArr);

}

function admin_menu()
{
    //是否有超级管理员，是则不则行权限验证
    if (auth()->user()->isRoot())
    {
        $menu =new \App\Repositories\MenusRepositories();
        return $menu->menusList();
    }
    else
    {
        return tree_array(auth()->user()->getMenus());
    }


}

/**
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 * 生成树列表  可以和treeToOrderList 配合生成分页的
 */
function listToTree($list, $pk='id',$pid = 'parent_id',$child = 'child',$root=0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 把Tree转换为有序列表
 * @return array
 */
function treeToOrderList($arr,$level=0,$filed='name',$child='child') {
    static $tree=array();
    if(is_array($arr)) {
        foreach ($arr as $key=>$val) {
            $val[$filed] = str_repeat('—', $level).$val[$filed];
            $tree[]=$val;
            if (isset($val[$child])) {
                treeToOrderList($val[$child],$level+1,$filed,$child);
            }
        }
    }
    return $tree;
}

/**
 * 相对地址转换为绝对地址
 * @param string $url
 * @return string
 */
function get_real_url($url = '')
{
    if (stripos($url, 'http') !== false || stripos($url, 'https') !== false) {
        return $url;
    } else {
        return '/'.$url;
        return request()->getSchemeAndHttpHost().'/'.$url;
    }
}


/**
 * 格式化数据化手机号码
 * @param $mobile
 * @return string
 */
function format_mobile($mobile)
{
    return substr($mobile, 0, 5) . "****" . substr($mobile, 9, 2);
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * 判断前端浏览器类型
 * @return bool|string
 */
function get_client_broswer()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];

    //微信内置浏览器
    if (stripos($ua, 'MicroMessenger')) {
        //preg_match('/MicroMessenger\/([\d\.]+)/i', $ua, $match);
        return "weixin";
    }
    //支付宝内置浏览器
    if (stripos($ua, 'AlipayClient')) {
        //preg_match('/AlipayClient\/([\d\.]+)/i', $ua, $match);
        return "alipay";
    }
    return false;
}

/**
 * @param $groupName
 * @return array
 * 获取配置
 */
function getConfigByGgroupName($groupName)
{
    return \App\Models\Config::query()->where('status', 1)
        ->where('group_name', $groupName)
        ->orderBy('id', 'asc')
        ->get()
        ->toArray();
}

function getImagesById($imagesId)
{
    return \App\Models\Images::query()->where('id',$imagesId)->pluck('url')->first();
}

function getConfigByName($name)
{
    return \Illuminate\Support\Facades\Cache::remember($name,10,function () use ($name){
        return \App\Models\Config::query()->where('name',$name)->pluck('value')->first();
    });

}

function get_thumb($imagesId)
{
    $thumb= getImagesById($imagesId);
    if(empty($thumb))
    {
        return asset('static/frontend/default/img/news_img1.jpg');
    }

    return $thumb;
}



function frontend($view = null, $data = [], $mergeData = [])
{
    if(!empty($view))
    {
        $view ='frontend.'.$view;
    }
    return view($view , $data, $mergeData);
}

function list_category()
{
    $cat = new \App\Repositories\CategoryRepositories();
    return $cat->allCategory();
}

function get_page_links($id)
{
    return route('page',$id);
}

function get_post_links($id)
{
    return route('post',$id);
}

function get_permalink($slug)
{
    return route('show',$slug);
}

function mini_program_list()
{
    return [
        10=>'微信小程序',
        20=>'支付宝小程序',
        30=>'百度小程序',
        40=>'抖音小程序',
    ];
}

if (!function_exists('time_ago')) {
    /**
     * 把日期或者时间戳转为距离现在的时间
     *
     * @param $time
     *
     * @return bool|string
     */

    function time_ago($posttime)
    {
        if (!is_int($posttime)) {
            $posttime = strtotime($posttime);
        }
        //当前时间的时间戳
        $nowtimes = time();
        //相差时间戳
        $counttime = $nowtimes - $posttime;

        //进行时间转换
        if ($counttime <= 60) {
            return '刚刚';
        } else if ($counttime > 60 && $counttime <= 120) {
            return '1分钟前';
        } else if ($counttime > 120 && $counttime <= 180) {
            return '2分钟前';
        } else if ($counttime > 180 && $counttime < 3600) {
            return intval(($counttime / 60)) . '分钟前';
        } else if ($counttime >= 3600 && $counttime < 3600 * 24) {
            return intval(($counttime / 3600)) . '小时前';
        } else if ($counttime >= 3600 * 24 && $counttime < 3600 * 24 * 2) {
            return '昨天';
        } else if ($counttime >= 3600 * 24 * 2 && $counttime < 3600 * 24 * 3) {
            return '前天';
        } else if ($counttime >= 3600 * 24 * 3 && $counttime <= 3600 * 24 * 7) {
            return intval(($counttime / (3600 * 24))) . '天前';
        } else if ($counttime >= 3600 * 24 * 7 && $counttime <= 3600 * 24 * 30) {
            return intval(($counttime / (3600 * 24 * 7))) . '周前';
        } else if ($counttime >= 3600 * 24 * 30 && $counttime <= 3600 * 24 * 365){
            return intval(($counttime / (3600 * 24 * 30))) . '个月前';
        } else if ($counttime >= 3600 * 24 * 365) {
            return intval(($counttime / (3600 * 24 * 365))). '年前';
        }
    }

}



if (!function_exists('cut_str')) {
    /**
     * 字符串截取，支持中文和其他编码
     *
     * @param string $str     需要转换的字符串
     * @param int    $start   开始位置
     * @param string $length  截取长度
     * @param bool   $suffix  截断显示字符
     * @param string $charset 编码格式
     *
     * @return string
     */
    function cut_str($str, $start, $length, $suffix = true, $charset = 'utf-8')
    {
        $str =strip_tags($str);
        $slice = mb_substr($str, $start, $length, $charset);
        $omit  = mb_strlen($str) >= $length ? '...' : '';

        return $suffix ? $slice . $omit : $slice;
    }
}